package com.shunwang.tools.httpclientsupport.support;

import java.io.IOException;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shunwang.tools.httpclientsupport.client.AbstractHttpClientNode;
import com.shunwang.tools.httpclientsupport.pool.Pool;
import com.shunwang.tools.httpclientsupport.transform.QueryTransform;

public class HttpClientWithTransformTemplate extends HttpClientTemplet {

	protected static Logger logger = LoggerFactory.getLogger("transformClientTemplate");
	
	private QueryTransform transform;

	public HttpClientWithTransformTemplate(HttpClientExecutor executor) {
		super(executor);
	}

	public HttpClientWithTransformTemplate(Pool pool) {
		super(pool);
	}
	
	/**
	 * 执行相关查询
	 * @param pair 查询参数
	 * @return 服务端返回信息
	 */
	public String execute(final NameValuePair pair){
		return (String)this.doExecutor(new AbstractHttpClientCallBack(){
			public String doHttpClient(AbstractHttpClientNode client) throws HttpException, IOException {
				return client.sendPost(pair);
			}
		});
	}
	/**
	 * 执行相关查询
	 * @param pairs 查询参数
	 * @return 服务器返回信息
	 */
	public String execute(final NameValuePair[] pairs){
		return (String)this.doExecutor(new AbstractHttpClientCallBack() {
			public Object doHttpClient(AbstractHttpClientNode client) throws HttpException, IOException {
				return client.sendPost(pairs);
			}
		});
	}
	
	public String execute(final Object obj){
		if(transform == null){
			if(hasThrows){
				throw new NullPointerException("transform can't configure when HttpClientWithStringTemplate invoke");
			}
			if(logger.isInfoEnabled()){
				logger.info("transform can't configure when HttpClientWithStringTemplate invoke");
				return null;
			}
		}
		return (String)this.doExecutor(new AbstractHttpClientCallBack() {
			public Object doHttpClient(AbstractHttpClientNode client) throws Exception {
				return client.sendPost(transform.transform(obj));
			}
		});
	}
	
	
	//-- getter setter -/
	public QueryTransform getTransform() {
		return transform;
	}

	public void setTransform(QueryTransform transform) {
		this.transform = transform;
	}
	
}
